package logic

import (
	"context"
	"encoding/json"
	"library/models/cache"
	"library/models/mysql"
	"strconv"
	"time"

	"library/libraryrpc/internal/svc"
	"library/libraryrpc/libraryrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type InformationListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewInformationListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InformationListLogic {
	return &InformationListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *InformationListLogic) InformationList(in *libraryrpc.InformationListRequest) (*libraryrpc.InformationListResponse, error) {
	// todo: add your logic here and delete this line
	var Informations []mysql.Information
	offset := (in.Page - 1) * in.Size
	itoa := strconv.Itoa(int(in.Page))
	itoaSize := strconv.Itoa(int(in.Size))

	get := cache.RedisDB.Get(l.ctx, "list"+itoa+itoaSize)

	if get.Val() == "" {
		mysql.DB.Offset(int(offset)).Limit(int(in.Size)).Order("created_at DESC").Find(&Informations)
		marshal, _ := json.Marshal(Informations)
		cache.RedisDB.Set(l.ctx, "list"+itoa+itoaSize, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &Informations)
	}

	var InformationList []*libraryrpc.InformationList
	for _, Information := range Informations {
		list := libraryrpc.InformationList{
			Title:         Information.Title,
			Desc:          Information.Desc,
			Number:        Information.Number,
			UserId:        int64(Information.UserId),
			InformationId: int64(Information.ID),
		}
		InformationList = append(InformationList, &list)
	}
	return &libraryrpc.InformationListResponse{
		List: InformationList,
	}, nil
}
